<template>
  <nut-loading-page :loading="loading" />
  <user-area v-show="!loading" :userInfo="userInfo"></user-area>
  <view v-show="!loading" class="function-list">
    <nut-grid v-if="functionListBuilded.length" :column-num="3" :border="false" square>
      <nut-grid-item v-for="(item, index) in functionListBuilded" :key="index" :text="item.title" @click="handleGo(item)">
        <nut-icon font-class-name="iconfont" class-prefix="icon" :name="item.name" size="40" />
      </nut-grid-item>
    </nut-grid>
    <view v-else class="no-content">
      <view class="h2">您没有使用本应用的权限</view>
      <view class="p">此应用仅供内部使用，如无相关权限，敬请离开！</view>
      <view class="p">如有疑问请联系管理员！</view>
    </view>
  </view>
</template>

<script>
  export default {
    name: 'home'
  }
</script>
<script setup>
import { reactive, ref } from 'vue'
import { wxLogin, getDict, editifOpenId } from "@/api/index";
import UserArea from "@/components/userArea.vue"
import { getPermissions } from '@/utils'

const loading = ref(true)
const userInfo = reactive({})
const role = {
  check: [103, 106, 107, 115],
  task: [101, 102, 110],
  fire: [112],
  patrol: [115],
}
/* 判断是否已授权 */
/* const judge = () => {
  if(!userInfo){
    isAuthorize()
  }
} */
const functionList = reactive([
  {
    name: 'qiye',
    title: '企业检查',
    path: '/pages/enterpriseInspection/index',
    auth: ':companyrecord',
    role: role.check,
    exclude: []
  },
  {
    name: 'changsuo',
    title: import.meta.env.VITE_APP_TYPE === 'new' ? '九小场所检查' : '场所检查',
    path: '/pages/storeInspection/index',
    auth: ':record',
    role: role.check,
    exclude: [201]
  },
  {
    name: 'fanghuo',
    title: '防火检查',
    path: '/pages/fireInspection/index',
    auth: ':fireRecord',
    role: role.fire,
    exclude: []
  },
  {
    name: 'xuncha',
    title: '巡查记录',
    path: '/pages/patrol/index',
    auth: ':patrol',
    role: role.patrol,
    exclude: []
  },
  {
    name: 'lvzhi',
    title: '履职任务',
    path: '/pages/tasks/index',
    auth: ':task',
    role: role.task,
    exclude: []
  },
  {
    name: 'yingji',
    title: '应急演练',
    path: '/pages/drill/index',
    auth: ':drill',
    role: role.check,
    exclude: []
  },
  {
    name: 'jiaoyu',
    title: '教育培训',
    auth: ':train',
    path: '/pages/train/index',
    role: role.check,
    exclude: []
  },
  {
    name: 'tongzhi',
    title: '通知公告',
    auth: ':list',
    path: '/pages/notice/index',
    role: [],
    exclude: []
  },
  {
    name: 'yuanquguanli',
    title: '园区管理',
    auth: ':aqjcGardenInfo',
    path: '/pages/park/index',
    role: [],
    exclude: []
  }
])
const functionListBuilded = ref([])
const buildFunctionList = (list, userRoleIds, deptId) => {
  try {
    // return list.filter(item => (userRoleIds.some(id => item.role.includes(id)) && !item.exclude.includes(deptId))) || []
    // console.log(getPermissions(item.auth))
    return list.filter(item => getPermissions(item.auth)) || []
  } catch (e) {
    return []
  }
}
const handleGo = (item) => {
  if ([].includes(item.name)) {
    uni.showToast({
      title: '功能开发中！',
      icon: 'error'
    })
    return
  }
  if (['lvzhi'].includes(item.name)) {
    uni.requestSubscribeMessage({
      tmplIds: ['9ICYju_MIg0179W9QHjWWFfnW9lzzopGvmWMm7n64Ds'], // lz模板id
      success (res) {
        console.log('msg', res)
        uni.navigateTo({
          url: userInfo.roleIds.includes(110) ? '/pages/tasks/filter' : item.path
        })
      },
      fail(err) {
        console.log('msgerr', err)
      }
    })
    return
  }
  uni.navigateTo({
    url: item.path
  })
}
const buildDict = () => {
  getDict().then(res => {
    console.log('dictres', res)
    const data = res.data
    const dict = {
      store_status: [],
      check_status: [],
      store_type: [],
      task_status: [],
      mountain_data: [],
      sys_comp_scale: [],
      sys_comp_type: [],
    }
    for (let i = 0; i < data.length; i++) {
      dict[data[i].dict_type] = [
          ...dict[data[i].dict_type],
          ...[
                {
                  code: data[i].dict_code,
                  text: data[i].dict_label,
                  value: data[i].dict_value,
                  type: data[i].list_class
                }
          ]
      ]
    }
    console.log('dict', dict)
    uni.setStorageSync('dict', dict)
  })
}
const login = () => {
  uni.login({
    provider: 'weixin',
    success: (res) => {
      console.log('res', res)
      const params = {
        code: res.code
      }
      loading.value = true
      wxLogin(params).then(async res => {
        console.log('login', res)
        await uni.setStorageSync('token', res.data.token)
        Object.assign(userInfo, res.data)
        await uni.setStorageSync('userInfo', res.data)
        functionListBuilded.value = buildFunctionList(functionList)
        await buildDict()
        loading.value = false
        if(!uni.getStorageSync('userInfo').ifOpenId || uni.getStorageSync('userInfo').ifOpenId == '0'){
          isAuthorize()
        }
      })
    }
  })
}
login()
/* 授权消息推送 */
const isAuthorize = () => {
  uni.showModal({
    title: '消息推送提示',
    content: '您之前拒绝了消息推送，为了及时获取最新信息，是否重新授权接收消息?',
    success: res => {
      if (res.confirm) {
        uni.requestSubscribeMessage({
          tmplIds: ['H_gOK53FXGagB5YiFBn37Iv5rfv62O2A7pSJthlZO3s'], // lz公告通知模板id
          // tmplIds: ['pENFKPBZwDmCtCJMc_GvOjq97S49LRY7sKxDzoNHYYA'], // ksh公告通知模板id
          success: (res) => {
            editifOpenId({openId: uni.getStorageSync('userInfo').openId}).then(res => {
              // console.log(res)
              if(res.code == 200){
                uni.showToast({
                  title: '授权成功'
                })
              }else{
                uni.showToast({
                  title: res.msg
                })
              }
              
            })
          },
          fail (err) {
            console.log(err)
          }
        })
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
}

</script>
<style scoped>
.function-list{padding: 20px 0 0;}
.no-content{padding: 20px 20px;text-align: center;}
.no-content .h2{color: #ff0000;font-size: 24px;font-weight: bold;margin: 0 0 20px;}
.no-content .p{margin: 0 0 10px;}
</style>
<style lang="scss">
.function-list .nut-grid-item__text{padding: 10px 0 0;}
</style>
